#include "head.h"

// 初始化tcps(qt服务器)
int init_qt_network()
{
    int qt_fd;
    // 1.创建等待QT端通信服务器
    qt_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (qt_fd < 0)
    {
        perror("socket qt_fd error.");
        return -1;
    }
    // 2.填充结构体
    struct sockaddr_in qtServeraddr, qtClientaddr;
    // 1》填充QT通信server端结构体
    qtServeraddr.sin_family = AF_INET;
    qtServeraddr.sin_port = htons(8888);
    qtServeraddr.sin_addr.s_addr = INADDR_ANY;

    socklen_t len = sizeof(struct sockaddr_in);

    // 3-1.绑定QT server端
    if (bind(qt_fd, (const struct sockaddr *)&qtServeraddr, len) < 0)
    {
        perror("bind QT_server error.");
        return -1;
    }
    // 3-2.监听
    if (listen(qt_fd, 5) < 0)
    {
        perror("listen QT error.");
        return -1;
    }

    return qt_fd;
}

// 初始化tcpc(haas客户端)
int init_haas_network(const char *ip, int haas_port)
{
    int haas_fd = -1;
    // 1.创建hass客户端通信
    haas_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (haas_fd < 0)
    {
        perror("socket hass_fd error.");
        return -1;
    }

    struct sockaddr_in haasServeraddr;
    // 2.填充QT通信server端结构体
    haasServeraddr.sin_family = AF_INET;
    haasServeraddr.sin_port = htons(haas_port);
    haasServeraddr.sin_addr.s_addr = inet_addr(ip);

    // 连接haas设备
    if (connect(haas_fd, (struct sockaddr *)&haasServeraddr, sizeof(struct sockaddr_in)) < 0)
    {
        perror("connect haas error.");
        return -1;
    }
    return haas_fd;
}

int wait_connect(int qt_fd)
{
    int acceptfd;
    struct sockaddr_in sockaddr;
    socklen_t len = sizeof(struct sockaddr_in);
    // 阻塞等待QT客户端连接
    acceptfd = accept(qt_fd, (struct sockaddr *)&sockaddr, &len);
    if (acceptfd < 0)
    {
        perror("accept error.");
        return -1;
    }
    printf("QT_clietn ip:%s port:%d\n", (char *)inet_ntoa(sockaddr.sin_addr), ntohs(sockaddr.sin_port));
    return acceptfd;
}

MSG_t read_data(int fd)
{
    int recvbyte;
    MSG_t recv_msg;
    // 接收haas发过来的数据
    recvbyte = recv(fd, &recv_msg, sizeof(recv_msg), 0);
    if (recvbyte < 0)
    {
        // perror("recv haas error.");
        recv_msg.type = 0;
        return recv_msg;
    }
    return recv_msg;
}

int write_data(int fd, MSG_t recv_msg)
{
    return send(fd, &recv_msg, sizeof(recv_msg), 0);
}

int create_thread(pthread_t tid, void *(*thread)(void *arg))
{
    return pthread_create(&tid, NULL, thread, NULL);
}